package org.keyyond.ms.core.util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import org.keyyond.ms.core.exception.FDFBRuntimeException;

import sun.misc.BASE64Encoder;

public class Util {

	/**
	 * 去除字符串中的回车
	 * 
	 * @param str
	 * @return
	 */
	public static String replaceBlank(String str) {
		String dest = "";
		if (str != null) {
			Pattern p = Pattern.compile("\\s*|\r|\n");
			Matcher m = p.matcher(str);
			dest = m.replaceAll("");
		}
		return dest;
	}

	/**
	 * MD%加密
	 * 
	 * @author YCR
	 * @param
	 * @return String
	 * @throws
	 */
	public static String EncoderByMd5(String str)
			throws NoSuchAlgorithmException, UnsupportedEncodingException {
		// 确定计算方法
		MessageDigest md5 = MessageDigest.getInstance("MD5");
		BASE64Encoder base64en = new BASE64Encoder();
		// 加密后的字符串
		String newstr = base64en.encode(md5.digest(str.getBytes("utf-8")));
		return newstr;
	}

	public static String sha256_HMAC(String message, String secret) {
		String hash = "";
		try {
			Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
			SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(),
					"HmacSHA256");
			sha256_HMAC.init(secret_key);
			byte[] bytes = sha256_HMAC.doFinal(message.getBytes());
			hash = byteArrayToHexString(bytes);
			System.out.println(hash);
		} catch (Exception e) {
			System.out.println("Error HmacSHA256 ===========" + e.getMessage());
		}
		return hash;
	}

	private static String byteArrayToHexString(byte[] b) {
		StringBuilder hs = new StringBuilder();
		String stmp;
		for (int n = 0; b != null && n < b.length; n++) {
			stmp = Integer.toHexString(b[n] & 0XFF);
			if (stmp.length() == 1)
				hs.append('0');
			hs.append(stmp);
		}
		return hs.toString().toLowerCase();
	}

	/**
	 * 获取唯一键 UUID
	 * 
	 * @return
	 */
	public static String generateUUID() {
		return UUID.randomUUID().toString();
	}

	public static String lFillZero(String str, int targetLength) {
		if (str == null || "".equals(str)) {
			throw new FDFBRuntimeException("UUID generated failed");
		} else {
			int length = str.length();
			for (int i = 0; i < (targetLength - length); i++) {
				str = "0" + str;
			}
			return str;
		}

	}

	/**
	 * 生成6位随机字符串
	* @author allan
	* @param size 位数
	* @return 返回内容 6位随机字符串
	 */
    public static String randomStr(int size) {
        String a = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        char[] rands = new char[size];
        for (int i = 0; i < rands.length; i++)
        {
            int rand = (int) (Math.random() * a.length());
            rands[i] = a.charAt(rand);
        }
        return new String(rands);
    }

    /**
     * MD5加密方法
    * @author allan
    * @param param 待加密字符串
    * @return 返回内容 加密后的MD5字符串（全部大写）
     */
    public static String generateSign(String param)
    {
    	try {
			return Md5.getEncode(param).toUpperCase();
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
    }
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		// for (int j = 0; j < 10000; j++) {
		// Set<String> testSet = new HashSet<String>();
		// for (int i = 0; i < 5000; i++) {
		// testSet.add(UUID.randomUUID().toString());
		// }
		// if (testSet.size() < 5000)
		// System.out.println(testSet.size());
		// }
		String message = "{start: 0, number: 20, sort: \"asc\"}";
		String str = "a500f3da-966a-4aca-85d0-fa2e6c3213c6";
		System.out.println(sha256_HMAC(message, str));
	}

}
